// 初始化工单列表
$(function() {
    var table = $('#example').DataTable({
        "dom": '<"top"f>rt<"bottom"ip><"clear">',
        "ajax": {
            "url": MANAGE_URL + '/getListPart',
            // "url": "../js/jsonData/parts_fee.json",//test
            // "dataSrc": ""//test
            "dataSrc": "data"
        },
        "columns": [
            { 
                "data": "productGroup",
                "render": function(data, type, full, meta) {
                    return full.basicProductSerial.basicProductGroup.productGroup;
                },
                "class": "center"
            },
            {
                "data": "serialCode",
                "render": function(data, type, full, meta) {
                    return full.basicProductSerial.serialCode;
                },
                "class": "center"
            },
            { "data": "sparepartName", "class": "center" },
            { "data": "money", "class": "center" },
            {
                "render": function(data, type, full, meta) {
                    return '<button type="button" class="am-btn am-btn-default purple edit-btn">修改</button>';
                },
                "class": "center"
            },
        ],
        "ordering": false,
    });
    $("tbody", '#example').on("click",".edit-btn",function(){
        var tds=$(this).parents("tr").children();
        $.each(tds, function(i,val){
            var jqob=$(val);
            if( i < 2 || jqob.has('button').length ){return true;}//跳过第1项 序号,按钮
            var txt=jqob.text();
            let put;
            if(i === 3){
                put = $("<input type='number' style='width: 100%;'>");
            }else{
                put=$("<input type='text' style='width: 100%;'>");
            }
            put.val(txt);
            jqob.html(put);
        });
        $(this).html("保存");
        $(this).toggleClass("edit-btn");
        $(this).toggleClass("save-btn");
    });

    $("tbody", '#example').on("click",".save-btn",function(){
        var that = this;
        var row=table.row($(this).parents("tr"));
        
        var tds=$(this).parents("tr").children();
        $.each(tds, function(i,val){
            var jqob=$(val);
            //把input变为字符串
            if(!jqob.has('button').length && i > 1){
                var txt=jqob.children("input").val();
                jqob.html(txt);
                table.cell(jqob).data(txt);//修改DataTables对象的数据
            }
        });
        var data=row.data();

        let option = {
            url: MANAGE_URL + "/savePartFee",
            data:{ data: JSON.stringify(data)},
            type:"post",
            success:function(res, textStatus){
                if(res.msg === 'success'){
                    alert('修改成功!');
                    $(that).html("编辑");
                    $(that).toggleClass("edit-btn");
                    $(that).toggleClass("save-btn");
                    Server.getFromCommon("/initProductSerial",{}, function(res){
                        console.log(res);
                    });
                }else{
                    alert('修改失败，请稍后重试！');
                    option.errorBack();
                }
             },
             error:function(XMLHttpRequest, textStatus, errorThrown){
                option.errorBack();
             },
             errorBack:function(){
                $.each(tds, function(i,val){
                    var jqob=$(val);
                    if( i < 2 || jqob.has('button').length ){return true;}//跳过第1项 序号,按钮
                    var txt=jqob.text();
                    let put;
                    if(i === 3){
                        put = $("<input type='number' style='width: 100%;'>");
                    }else{
                        put=$("<input type='text' style='width: 100%;'>");
                    }
                    put.val(txt);
                    jqob.html(put);
                });
             }
        }
        $.ajax(option);
    });
    initFileInput({elem:"#file-1"});
    initFileInput({elem:"#file-2"});
    
    var SERVER_IMAGE = [
        '<div class="file-preview-frame" id="preview-{#id}" href="{#src}">',
		'<img src="{#src}" class="file-preview-image" style="width:auto;height:160px;"></div>'
    ].join('');
    uploadFile({elem:"#file-1", type: 0});
    uploadFile({elem:"#file-2", type: 1});
    // updateServerFeeFile
    Server.getFromCommon("/listServerFeeFile", {}, function(res){
        console.log(res.data);
        for(let i = 0 ; i < 2; i++){
            let installImage = getCosFile(res.data[i].fileName);
            $('.file-preview-thumbnails').eq(i).attr("id", "light-gallery-"+i).html(SERVER_IMAGE.replace("{#id}", res.data[i].id).replace(new RegExp("{#src}","gm"), installImage));
            $('span.file-input').removeClass('file-input-new');
            lightGallery( document.getElementById("light-gallery-"+i) );
        }
        //默认隐藏上传和移除按钮
        $('.fileinput-remove-button').hide();
        $('.fileinput-upload-button').hide();
    });
});

function initFileInput(param){
    let option = {
        language: 'zh', //设置语言
        allowedFileExtensions: ['jpg', 'gif', 'png'], //接收的文件后缀
        showUpload: true,
        showCaption: false,
        browseClass: "btn btn-primary",
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>"
    }
    $.extend(option, param.option);
    $(param.elem).fileinput(option).on("change", function(){
        //显示移除和上传按钮
        $(this).parent().prev().show();
        $(this).parents('.file-input').find('.fileinput-remove-button').show();
    });
}

function uploadFile(option){
    $(option.elem).parents('.file-input').find('.fileinput-upload-button').on('click', function(e){
        var file = $(option.elem)[0].files[0];
        var curTiem = new Date().getTime();
        var param = {
            file:file,
            success:function (err, data) {
                if (err) {
                   alert("上传失败!")
                    return;
                }
                if (data.statusCode === 200) {
                    console.log(this.Key);
                    console.log(data);
                    Server.postToManage('/updateServerFeeFile', {file: this.Key, type: option.type}, function(res){
                        alert("上传成功!");
                        var span = $(option.elem).parents('.file-input');
                        //默认隐藏上传和移除按钮
                        span.find('.fileinput-remove-button').hide();
                        span.find('.fileinput-upload-button').hide();
                    });
                }
            },
            curTiem:curTiem
        }
        uploadToCos(param);
    });
}